<?php

namespace App\Listeners;

use App\Config;
use App\Events\Distribution;
use App\Order;
use App\User;
use App\UserBalanceRecord;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class HandleDistribution
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  Distribution  $event
     * @return void
     */
    public function handle(Distribution $event)
    {
        $this->_byGoods($event->order);
    }

    /**
     * 按单品设置分销提成
     * @param Order $order
     */
    protected function _byGoods(Order $order) {
        // 购买商品的用户
        $user = User::find($order->user_id);
        $orderGoods =  $order->orderGoods;
        if ($user && $user->parent_id != 0) {
            $pUser = User::find($user->parent_id);
            if ($pUser) {
                // 一级提成
                foreach ($orderGoods as $oGoods) {
                    if ($oGoods->goods->bonus_ratio_1 > 0) {
                        $bonus = floatval($oGoods->goods_price * $oGoods->goods_num * $oGoods->goods->bonus_ratio_1);
                        $pUser->balance = $pUser->balance + $bonus;
                        $pUser->save();
                        // 记录
                        UserBalanceRecord::create([
                            'user_id' => $pUser->id,
                            'type' => 1,
                            'type_desc' => 'DISTRIBUTION',
                            'status' => 1,
                            'amount' => $bonus,
                            'trade_no' => $order->order_sn,
                            'comment' => "用户{$user->name}购买商品，获得分销提成"
                        ]);
                    }
                }
                // 二级提成
                $ppUser = User::find($pUser->parent_id);
                if ($ppUser) {
                    foreach ($orderGoods as $oGoods) {
                        if ($oGoods->goods->bonus_ratio_2 > 0) {
                            $bonus = floatval($oGoods->goods_price * $oGoods->goods_num * $oGoods->goods->bonus_ratio_2);
                            $ppUser->balance = $ppUser->balance + $bonus;
                            $ppUser->save();
                            // 记录
                            UserBalanceRecord::create([
                                'user_id' => $ppUser->id,
                                'type' => 1,
                                'type_desc' => 'DISTRIBUTION',
                                'status' => 1,
                                'amount' => $bonus,
                                'trade_no' => $order->order_sn,
                                'comment' => "用户{$user->name}购买商品，获得分销提成"
                            ]);
                        }
                    }
                }
            }
        }
    }
}
